package com.cttic.erp.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cttic.erp.bean.BusiExpenseAccountRecordBean;
import com.cttic.erp.bean.InfoProjectBean;
import com.cttic.erp.bean.SysParamBean;
import com.cttic.erp.bean.ext.BusiExpenseAccountRecordBeanExt;
import com.cttic.erp.bean.ext.InfoOperBeanExt;
import com.cttic.erp.common.constants.BusiConstants;
import com.cttic.erp.common.util.CacheUtil;
import com.cttic.erp.common.util.ExceptionUtil;
import com.cttic.erp.common.util.InfoOperUtil;
import com.cttic.erp.common.util.StringUtil;
import com.cttic.erp.service.interfaces.IBusiExpenseAccountRecordService;
import com.cttic.erp.service.interfaces.IInfoEmployeeService;
import com.cttic.erp.service.interfaces.IInfoProjectService;

@Controller
@RequestMapping("/expenseAccount")
public class ExpenseAccountController {

	@Resource
	private IInfoEmployeeService infoEmployeeServiceImpl;
	
	@Resource
	private IBusiExpenseAccountRecordService busiExpenseAccountRecordServiceImpl;
	
	@Resource
	private IInfoProjectService infoProjectService;
	
	@RequestMapping(value = "/apply")
	public ModelAndView apply(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		// 获取当前操作员信息
		InfoOperBeanExt infoOperBean = InfoOperUtil.getCurrOperInfo(request);
		long employeeId = infoOperBean.getInfoEmployeeBean().getEmployee_id();
		List<BusiExpenseAccountRecordBean> busiExpenseAccountRecordBeans = busiExpenseAccountRecordServiceImpl.getBeansByEmployeeId(employeeId);
		modelMap.put("EXPENSE_ACCOUNT_EXPENSE_TYPE", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "EXPENSE_TYPE"));
		modelMap.put("EXPENSE_ACCOUNT_STATE", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "STATE"));
		modelMap.put("EXPENSE_ACCOUNT_RECORD", busiExpenseAccountRecordBeans);
		modelMap.put("PRJ_LIST", infoProjectService.getBeans());
		return new ModelAndView("expenseAccount/apply", modelMap);
	}
	
	@RequestMapping(value = "/save")
	public void save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		JSONObject rtnJson = new JSONObject();
		try {
			// 1、获取当前操作员信息
			InfoOperBeanExt infoOperBean = InfoOperUtil
					.getCurrOperInfo(request);
			long employeeId = infoOperBean.getInfoEmployeeBean()
					.getEmployee_id();
			// 2、获取页面操作标示
			String operType = request.getParameter("OPER_TYPE");
			String recordId = request.getParameter("RECORD_ID");
			String prjId = request.getParameter("prj_id");
			String expenseType = request.getParameter("expense_type");
			String expenseAmount = request.getParameter("expense_amount");
			String expenseDesc = request.getParameter("expense_desc");
			String state = request.getParameter("STATE");
			// 3、获取页面提交信息
			BusiExpenseAccountRecordBean bean = new BusiExpenseAccountRecordBean();
			// 4、根据操作类型分别进行操作
			if ("ADD".equals(operType)) {
				bean.setEmployee_id(employeeId);
				bean.setPrj_id(BigDecimal.valueOf(Long.parseLong(prjId)));
				bean.setExpense_type(expenseType);
				bean.setExpense_amount(new BigDecimal(expenseAmount));
				bean.setExpense_desc(expenseDesc.replaceAll("\n", "<br>"));
				bean.setState(1);
				bean.setApply_time(new Date());
				busiExpenseAccountRecordServiceImpl.insert(bean);
			} else if ("EDIT".equals(operType)) {
				bean.setRecord_id(Long.parseLong(recordId));
				bean.setPrj_id(BigDecimal.valueOf(Long.parseLong(prjId)));
				bean.setExpense_type(expenseType);
				bean.setExpense_amount(new BigDecimal(expenseAmount));
				bean.setExpense_desc(expenseDesc.replaceAll("\n", "<br>"));
				busiExpenseAccountRecordServiceImpl.update(bean);
			} else if ("CANCEL".equals(operType)) {
				bean.setRecord_id(Long.parseLong(recordId));
				bean.setState(0);
				busiExpenseAccountRecordServiceImpl.updateState(bean);
			} else if ("OPER".equals(operType)) {
				bean.setRecord_id(Long.parseLong(recordId));
				List<SysParamBean> sysParamBeanList = CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "STATE", "EXPENSE_ACCOUNT", "STATE", state);
				bean.setState(Integer.parseInt(sysParamBeanList.get(0).getColumn_value()));
				busiExpenseAccountRecordServiceImpl.updateState(bean);
			}
			rtnJson.put(BusiConstants.AjaxReturn.STATUS_CODE,
					BusiConstants.AjaxStatus.STATUS_SUCCESS);
			rtnJson.put(BusiConstants.AjaxReturn.STATUS_INFO, "提交成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			String retMsg = ex.getCause() == null ? ex.getMessage() : ex
					.getCause().getMessage();
			rtnJson = ExceptionUtil.toJSON(retMsg, ex, request);
		} finally {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter printWriter = response.getWriter();
			printWriter.write(rtnJson.toString());
			printWriter.flush();
			printWriter.close();
		}
	}
	
	@RequestMapping(value = "/confirm")
	public ModelAndView confirm(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		// 1、获取页面提交信息
		InfoOperBeanExt infoOperBean = InfoOperUtil
				.getCurrOperInfo(request);
		long employeeId = infoOperBean.getInfoEmployeeBean()
				.getEmployee_id();
		// 2、获取人员报销记录
		List<BusiExpenseAccountRecordBean> busiExpenseAccountRecordBeans = busiExpenseAccountRecordServiceImpl.getBeansByEmployeeId(employeeId);
			modelMap.put("EXPENSE_ACCOUNT_RECORD", busiExpenseAccountRecordBeans);
			modelMap.put("SELECT_EMPLOYEE", infoEmployeeServiceImpl
					.getBean(employeeId));
		modelMap.put("EXPENSE_ACCOUNT_EXPENSE_TYPE", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "EXPENSE_TYPE"));
		modelMap.put("EXPENSE_ACCOUNT_STATE", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "STATE"));
		modelMap.put("EXPENSE_ACCOUNT_OPER", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "OPER"));
		modelMap.put("PRJ_LIST", infoProjectService.getBeans());
		return new ModelAndView("expenseAccount/confirm", modelMap);
	}
	
	@RequestMapping(value = "/oper")
	public ModelAndView oper(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		// 1、获取页面提交信息
		String employeeId = request.getParameter("EMPLOYEE_ID");
		// 2、获取人员报销记录
		if (!StringUtil.isBlank(employeeId)) {
			List<BusiExpenseAccountRecordBean> busiExpenseAccountRecordBeans = busiExpenseAccountRecordServiceImpl.getBeansByEmployeeId(Long.parseLong(employeeId));
			modelMap.put("EXPENSE_ACCOUNT_RECORD", busiExpenseAccountRecordBeans);
			modelMap.put("SELECT_EMPLOYEE", infoEmployeeServiceImpl
					.getBean(Long.parseLong(employeeId)));
		} else {
			List<BusiExpenseAccountRecordBean> busiExpenseAccountRecordBeans = busiExpenseAccountRecordServiceImpl.getEffectBeans();
			modelMap.put("EXPENSE_ACCOUNT_RECORD", busiExpenseAccountRecordBeans);
		}
		modelMap.put("EXPENSE_ACCOUNT_EXPENSE_TYPE", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "EXPENSE_TYPE"));
		modelMap.put("EXPENSE_ACCOUNT_STATE", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "STATE"));
		modelMap.put("EXPENSE_ACCOUNT_OPER", CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "OPER"));
		modelMap.put("EMPLOYEE_LIST", infoEmployeeServiceImpl
				.getBeanList());
		modelMap.put("PRJ_LIST", infoProjectService.getBeans());
		return new ModelAndView("expenseAccount/oper", modelMap);
	}
	
	@RequestMapping(value = "/stat")
	public ModelAndView stat(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		List<InfoProjectBean> projectBeanList = infoProjectService.getBeans();
		Map<String, String> projectBeanMap = new HashMap<String, String>();
		for (InfoProjectBean bean : projectBeanList) {
			projectBeanMap.put(bean.getPrj_id().toString(), bean.getPrj_name());
		}
		List<SysParamBean> paramBeanList = CacheUtil.getSysParamBeanList("EXPENSE_ACCOUNT", "EXPENSE_TYPE");
		Map<String, String> paramBeanMap = new HashMap<String, String>();
		for (SysParamBean bean : paramBeanList) {
			paramBeanMap.put(bean.getColumn_value(), bean.getColumn_desc());
		}
		List<BusiExpenseAccountRecordBeanExt> busiExpenseAccountRecordBeanExts = busiExpenseAccountRecordServiceImpl.getStatBeans();
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (BusiExpenseAccountRecordBeanExt extBean : busiExpenseAccountRecordBeanExts) {
			String applyTime = extBean.getsApplyTime();
			BigDecimal prjId = extBean.getPrj_id();
			extBean.setPrjName(projectBeanMap.get(prjId.toString()));
			String expenseType = extBean.getExpense_type();
			extBean.setExpenseTypeName(paramBeanMap.get(expenseType));
			int timeCnt = 0;
			int prjCnt = 0;
			for (Map<String, Object> timeMap : resultList) {
				String statTime = timeMap.get("stat_time").toString();
				List<Map<String, Object>> prjList = (List<Map<String, Object>>) timeMap.get("prj_list");
				if (statTime.equals(applyTime)) {
					timeCnt ++;
					for (Map<String, Object> prjMap : prjList) {
						if (prjMap.get("stat_prj").toString().equals(prjId.toString())) {
							prjCnt ++;
						}
					}
				}
			}
			if (timeCnt == 0) {
				Map<String, Object> timeMap = new HashMap<String, Object>();
				timeMap.put("stat_time", applyTime);
				List<Map<String, Object>> prjList = new ArrayList<Map<String, Object>>();
				if (prjCnt == 0) {
					Map<String, Object> prjMap = new HashMap<String, Object>();
					prjMap.put("stat_prj", prjId.toString());
					prjMap.put("stat_prj_name", extBean.getPrjName());
					List<BusiExpenseAccountRecordBeanExt> beanList = new ArrayList<BusiExpenseAccountRecordBeanExt>();
					beanList.add(extBean);
					prjMap.put("stat_date", beanList);
					prjList.add(prjMap);
					timeMap.put("prj_list", prjList);
				}
				resultList.add(timeMap);
			} else {
				if (prjCnt == 0) {
					for (Map<String, Object> timeMap : resultList) {
						if (timeMap.get("stat_time").toString().equals(applyTime)) {
							List<Map<String, Object>> prjList = (List<Map<String, Object>>) timeMap.get("prj_list");
							Map<String, Object> prjMap = new HashMap<String, Object>();
							prjMap.put("stat_prj", prjId.toString());
							prjMap.put("stat_prj_name", extBean.getPrjName());
							List<BusiExpenseAccountRecordBeanExt> beanList = new ArrayList<BusiExpenseAccountRecordBeanExt>();
							beanList.add(extBean);
							prjMap.put("stat_date", beanList);
							prjList.add(prjMap);
							timeMap.put("prj_list", prjList);
						}
					}
				} else {
					for (Map<String, Object> timeMap : resultList) {
						if (timeMap.get("stat_time").toString().equals(applyTime)) {
							List<Map<String, Object>> prjList = (List<Map<String, Object>>) timeMap.get("prj_list");
							for (Map<String, Object> prjMap : prjList) {
								if (prjMap.get("stat_prj").toString().equals(prjId.toString())) {
									((List<BusiExpenseAccountRecordBeanExt>) prjMap.get("stat_date")).add(extBean);
								}
							}
						}
					}
				}
			}
		}
		
		modelMap.put("RESULT_LIST", resultList);
		return new ModelAndView("expenseAccount/stat", modelMap);
	}
}
